package com.ely.coupon.common.idempotent.service.impl;

import com.ely.coupon.common.core.ex.ServiceException;
import com.ely.coupon.common.core.result.ResponseCode;
import com.ely.coupon.common.idempotent.config.IdempotentProperties;
import com.ely.coupon.common.idempotent.service.TokenService;
import com.ely.coupon.common.redis.dao.RedisDao;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Array;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;

/**
 *
 */
public class TokenServiceImpl implements TokenService {
    public static final String IDEMPOTENT_TOKEN_PREFIX = "idempotent:token:";
    public static final String LUA_SCRIPT_PATH = "lua/idempotent.lua";
    @Resource
    private RedisDao redisDao;
    @Resource
    private IdempotentProperties idempotentProperties;
    @Resource
    RedisTemplate<String, String> redisTemplate;

    /**
     * @param id
     * @return
     */
    @Override
    public void createToken(Long id) {
//        String token = RandomUtil.randomString(18);
        try {
            // 使用String类型的过期时间
            redisDao.setEx(IDEMPOTENT_TOKEN_PREFIX + id, id, Duration.ofMinutes(10));
        } catch (Exception ex) {
            throw new ServiceException(ResponseCode.SYS_ERROR);
        }
    }

    /**
     * 原子操作
     * LUA
     *
     * @param request
     * @return
     */
    @Override
    public Boolean verifyToken(HttpServletRequest request) {
        String id = request.getParameter(idempotentProperties.getKey());
//        String token = request.getHeader("idempotent-token");
        if (!ObjectUtils.isEmpty(id)) {
            Integer execute = (Integer) redisDao.execute(LUA_SCRIPT_PATH, Collections.singletonList(IDEMPOTENT_TOKEN_PREFIX + id));
            return !ObjectUtils.isEmpty(execute) && execute == 1;
        }
        return false;
    }

}
